#include "StdAfx.h"
#include <xcommonfunc.h>
#include <tinyxml/tinyxml.h>
#include "DeskMgr.h"

CDeskMgr::CDeskMgr(void)
{
}

CDeskMgr::~CDeskMgr(void)
{
}

void CDeskMgr::ManageDesktop()
{
	LoadRuleConfig();

	TCHAR szDeskPath[MAX_PATH] = {0};
	GetDesktopDir(szDeskPath, MAX_PATH);
	EnumDesktop(szDeskPath);

	TCHAR szDeskTemp[MAX_PATH] = {0};
	_tcsncpy(szDeskTemp, szDeskPath, MAX_PATH);
	GetCommonDesktopDir(szDeskPath, MAX_PATH);
	EnumDesktop(szDeskPath, szDeskTemp);
}
void CDeskMgr::EnumDesktop(TCHAR * szDeskPath, TCHAR * szDesDeskPath)
{
	if (!szDeskPath || !_tcslen(szDeskPath))
	{
		return;
	}
	CString strFind = szDeskPath;
	strFind += L"\\*.*";

	WIN32_FIND_DATA fd = {0};

	HANDLE hFind = ::FindFirstFile(strFind, &fd);
	if (INVALID_HANDLE_VALUE == hFind) return;

	while (FindNextFile(hFind, &fd))
	{
		if (!_tcscmp(fd.cFileName, L".") || !_tcscmp(fd.cFileName, L".."))
		{
			continue;
		}
	
		TCHAR * pExt = ::PathFindExtension(fd.cFileName);
		if (pExt)
		{
			CString strExt = pExt;
			map<CString, CString>::iterator it = m_mRules.find(strExt);
			if (it != m_mRules.end())
			{
				CString strDirectory;
				if (szDesDeskPath)
				{
					strDirectory = szDesDeskPath;
				}
				else
				{
					strDirectory = szDeskPath;
				}

				strDirectory = strDirectory + L"\\" + m_mRules[strExt];
				if (!::PathFileExists(strDirectory))
				{
					::CreateDirectory(strDirectory, NULL);
				}
				CString strFile = szDeskPath;
				strFile = strFile + L"\\" + fd.cFileName;
				CString strNewFile = strDirectory + L"\\" + fd.cFileName;
				//::CopyFile(strFile, strNewFile, FALSE);
				BOOL bRet = FileOperation(strFile, strNewFile, FO_MOVE);
				if (!bRet)
				{
					int a = 0;
				}
			}
		}
	}

	FindClose(hFind);

}

BOOL CDeskMgr::LoadRuleConfig()
{
	TCHAR szPath[MAX_PATH] = {0};
	GetCurrentPath(szPath, MAX_PATH);
	::PathCombine(szPath, szPath, L"config.xml");

	USES_CONVERSION;
	TiXmlDocument xmlDoc( W2A(szPath) );
	bool bRet = xmlDoc.LoadFile();
	if ( !bRet )
	{
		return FALSE; 
	}

	TiXmlElement *pXmlRootElem = xmlDoc.RootElement();
	CString strValue = pXmlRootElem->Value();
	if (strValue.Compare(A2W("rules")))
	{
		return FALSE;
	}

	//////////////////////////////////////////////////////////////////////////////
	//TiXmlElement *pTiElement = NULL;
	TiXmlNode * pNode = NULL;
	pNode = pXmlRootElem->FirstChild("rule");

	while (pNode)
	{
		TiXmlElement *pXmlElem = pNode->ToElement();
		CString strFolder = CA2T(pXmlElem->Attribute("folder"), CP_ACP);
		CString strRule = CA2T(pXmlElem->Attribute("rule"), CP_ACP);
		pNode = pNode->NextSibling("rule");

		vector<CString>m_vSplit;
		SplitString(strRule, L";", m_vSplit);
		if (!m_vSplit.size())
		{
			m_mRules[strRule] = strFolder;
		}
		else
		{
			for (int i = 0; i < m_vSplit.size(); ++i)
			{
				m_mRules[m_vSplit[i]] = strFolder;
			}
		}

	}

	return TRUE;
}